home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / logging / config.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  11KB  |  375 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """
  5. Configuration functions for the logging package for Python. The core package
  6. is based on PEP 282 and comments thereto in comp.lang.python, and influenced
  7. by Apache's log4j system.
  8.  
  9. Should work under Python versions >= 1.5.2, except that source line
  10. information is not available unless 'sys._getframe()' is.
  11.  
  12. Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved.
  13.  
  14. To use, simply 'import logging' and log away!
  15. """
  16. import sys
  17. import logging
  18. import logging.handlers as logging
  19. import string
  20. import socket
  21. import struct
  22. import os
  23. import traceback
  24. import types
  25.  
  26. try:
  27.     import thread
  28.     import threading
  29. except ImportError:
  30.     thread = None
  31.  
  32. from SocketServer import ThreadingTCPServer, StreamRequestHandler
  33. DEFAULT_LOGGING_CONFIG_PORT = 9030
  34. if sys.platform == 'win32':
  35.     RESET_ERROR = 10054
  36. else:
  37.     RESET_ERROR = 104
  38. _listener = None
  39.  
  40. def fileConfig(fname, defaults = None, disable_existing_loggers = 1):
  41.     '''
  42.     Read the logging configuration from a ConfigParser-format file.
  43.  
  44.     This can be called several times from an application, allowing an end user
  45.     the ability to select from various pre-canned configurations (if the
  46.     developer provides a mechanism to present the choices and load the chosen
  47.     configuration).
  48.     In versions of ConfigParser which have the readfp method [typically
  49.     shipped in 2.x versions of Python], you can pass in a file-like object
  50.     rather than a filename, in which case the file-like object will be read
  51.     using readfp.
  52.     '''
  53.     import ConfigParser as ConfigParser
  54.     cp = ConfigParser.ConfigParser(defaults)
  55.     if hasattr(cp, 'readfp') and hasattr(fname, 'readline'):
  56.         cp.readfp(fname)
  57.     else:
  58.         cp.read(fname)
  59.     formatters = _create_formatters(cp)
  60.     logging._acquireLock()
  61.     
  62.     try:
  63.         logging._handlers.clear()
  64.         del logging._handlerList[:]
  65.         handlers = _install_handlers(cp, formatters)
  66.         _install_loggers(cp, handlers, disable_existing_loggers)
  67.     finally:
  68.         logging._releaseLock()
  69.  
  70.  
  71.  
  72. def _resolve(name):
  73.     '''Resolve a dotted name to a global object.'''
  74.     name = string.split(name, '.')
  75.     used = name.pop(0)
  76.     found = __import__(used)
  77.     for n in name:
  78.         used = used + '.' + n
  79.         
  80.         try:
  81.             found = getattr(found, n)
  82.         continue
  83.         except AttributeError:
  84.             __import__(used)
  85.             found = getattr(found, n)
  86.             continue
  87.         
  88.  
  89.     
  90.     return found
  91.  
  92.  
  93. def _strip_spaces(alist):
  94.     return map((lambda x: string.strip(x)), alist)
  95.  
  96.  
  97. def _create_formatters(cp):
  98.     '''Create and return formatters'''
  99.     flist = cp.get('formatters', 'keys')
  100.     if not len(flist):
  101.         return { }
  102.     flist = string.split(flist, ',')
  103.     flist = _strip_spaces(flist)
  104.     formatters = { }
  105.     for form in flist:
  106.         sectname = 'formatter_%s' % form
  107.         opts = cp.options(sectname)
  108.         if 'format' in opts:
  109.             fs = cp.get(sectname, 'format', 1)
  110.         else:
  111.             fs = None
  112.         if 'datefmt' in opts:
  113.             dfs = cp.get(sectname, 'datefmt', 1)
  114.         else:
  115.             dfs = None
  116.         c = logging.Formatter
  117.         if 'class' in opts:
  118.             class_name = cp.get(sectname, 'class')
  119.             if class_name:
  120.                 c = _resolve(class_name)
  121.             
  122.         
  123.         f = c(fs, dfs)
  124.         formatters[form] = f
  125.     
  126.     return formatters
  127.  
  128.  
  129. def _install_handlers(cp, formatters):
  130.     '''Install and return handlers'''
  131.     hlist = cp.get('handlers', 'keys')
  132.     if not len(hlist):
  133.         return { }
  134.     hlist = string.split(hlist, ',')
  135.     hlist = _strip_spaces(hlist)
  136.     handlers = { }
  137.     fixups = []
  138.     for hand in hlist:
  139.         sectname = 'handler_%s' % hand
  140.         klass = cp.get(sectname, 'class')
  141.         opts = cp.options(sectname)
  142.         if 'formatter' in opts:
  143.             fmt = cp.get(sectname, 'formatter')
  144.         else:
  145.             fmt = ''
  146.         
  147.         try:
  148.             klass = eval(klass, vars(logging))
  149.         except (AttributeError, NameError):
  150.             klass = _resolve(klass)
  151.  
  152.         args = cp.get(sectname, 'args')
  153.         args = eval(args, vars(logging))
  154.         h = klass(*args)
  155.         if 'level' in opts:
  156.             level = cp.get(sectname, 'level')
  157.             h.setLevel(logging._levelNames[level])
  158.         
  159.         if len(fmt):
  160.             h.setFormatter(formatters[fmt])
  161.         
  162.         if issubclass(klass, logging.handlers.MemoryHandler):
  163.             if 'target' in opts:
  164.                 target = cp.get(sectname, 'target')
  165.             else:
  166.                 target = ''
  167.             if len(target):
  168.                 fixups.append((h, target))
  169.             
  170.         
  171.         handlers[hand] = h
  172.     
  173.     for h, t in fixups:
  174.         h.setTarget(handlers[t])
  175.     
  176.     return handlers
  177.  
  178.  
  179. def _install_loggers(cp, handlers, disable_existing_loggers):
  180.     '''Create and install loggers'''
  181.     llist = cp.get('loggers', 'keys')
  182.     llist = string.split(llist, ',')
  183.     llist = map((lambda x: string.strip(x)), llist)
  184.     llist.remove('root')
  185.     sectname = 'logger_root'
  186.     root = logging.root
  187.     log = root
  188.     opts = cp.options(sectname)
  189.     if 'level' in opts:
  190.         level = cp.get(sectname, 'level')
  191.         log.setLevel(logging._levelNames[level])
  192.     
  193.     for h in root.handlers[:]:
  194.         root.removeHandler(h)
  195.     
  196.     hlist = cp.get(sectname, 'handlers')
  197.     if len(hlist):
  198.         hlist = string.split(hlist, ',')
  199.         hlist = _strip_spaces(hlist)
  200.         for hand in hlist:
  201.             log.addHandler(handlers[hand])
  202.         
  203.     
  204.     existing = root.manager.loggerDict.keys()
  205.     existing.sort()
  206.     child_loggers = []
  207.     for log in llist:
  208.         sectname = 'logger_%s' % log
  209.         qn = cp.get(sectname, 'qualname')
  210.         opts = cp.options(sectname)
  211.         if 'propagate' in opts:
  212.             propagate = cp.getint(sectname, 'propagate')
  213.         else:
  214.             propagate = 1
  215.         logger = logging.getLogger(qn)
  216.         if qn in existing:
  217.             i = existing.index(qn)
  218.             prefixed = qn + '.'
  219.             pflen = len(prefixed)
  220.             num_existing = len(existing)
  221.             i = i + 1
  222.             while i < num_existing and existing[i][:pflen] == prefixed:
  223.                 child_loggers.append(existing[i])
  224.                 i = i + 1
  225.             existing.remove(qn)
  226.         
  227.         if 'level' in opts:
  228.             level = cp.get(sectname, 'level')
  229.             logger.setLevel(logging._levelNames[level])
  230.         
  231.         for h in logger.handlers[:]:
  232.             logger.removeHandler(h)
  233.         
  234.         logger.propagate = propagate
  235.         logger.disabled = 0
  236.         hlist = cp.get(sectname, 'handlers')
  237.         if len(hlist):
  238.             hlist = string.split(hlist, ',')
  239.             hlist = _strip_spaces(hlist)
  240.             for hand in hlist:
  241.                 logger.addHandler(handlers[hand])
  242.             
  243.     
  244.     for log in existing:
  245.         logger = root.manager.loggerDict[log]
  246.         if log in child_loggers:
  247.             logger.level = logging.NOTSET
  248.             logger.handlers = []
  249.             logger.propagate = 1
  250.             continue
  251.         if disable_existing_loggers:
  252.             logger.disabled = 1
  253.             continue
  254.     
  255.  
  256.  
  257. def listen(port = DEFAULT_LOGGING_CONFIG_PORT):
  258.     '''
  259.     Start up a socket server on the specified port, and listen for new
  260.     configurations.
  261.  
  262.     These will be sent as a file suitable for processing by fileConfig().
  263.     Returns a Thread object on which you can call start() to start the server,
  264.     and which you can join() when appropriate. To stop the server, call
  265.     stopListening().
  266.     '''
  267.     if not thread:
  268.         raise NotImplementedError, 'listen() needs threading to work'
  269.     thread
  270.     
  271.     class ConfigStreamHandler(StreamRequestHandler):
  272.         '''
  273.         Handler for a logging configuration request.
  274.  
  275.         It expects a completely new logging configuration and uses fileConfig
  276.         to install it.
  277.         '''
  278.         
  279.         def handle(self):
  280.             '''
  281.             Handle a request.
  282.  
  283.             Each request is expected to be a 4-byte length, packed using
  284.             struct.pack(">L", n), followed by the config file.
  285.             Uses fileConfig() to do the grunt work.
  286.             '''
  287.             import tempfile as tempfile
  288.             
  289.             try:
  290.                 conn = self.connection
  291.                 chunk = conn.recv(4)
  292.                 if len(chunk) == 4:
  293.                     slen = struct.unpack('>L', chunk)[0]
  294.                     chunk = self.connection.recv(slen)
  295.                     while len(chunk) < slen:
  296.                         chunk = chunk + conn.recv(slen - len(chunk))
  297.                     file = tempfile.mktemp('.ini')
  298.                     f = open(file, 'w')
  299.                     f.write(chunk)
  300.                     f.close()
  301.                     
  302.                     try:
  303.                         fileConfig(file)
  304.                     except (KeyboardInterrupt, SystemExit):
  305.                         raise 
  306.                     except:
  307.                         traceback.print_exc()
  308.  
  309.                     os.remove(file)
  310.             except socket.error:
  311.                 e = None
  312.                 if type(e.args) != types.TupleType:
  313.                     raise 
  314.                 type(e.args) != types.TupleType
  315.                 errcode = e.args[0]
  316.                 if errcode != RESET_ERROR:
  317.                     raise 
  318.                 errcode != RESET_ERROR
  319.  
  320.  
  321.  
  322.     
  323.     class ConfigSocketReceiver(ThreadingTCPServer):
  324.         '''
  325.         A simple TCP socket-based logging config receiver.
  326.         '''
  327.         allow_reuse_address = 1
  328.         
  329.         def __init__(self, host = 'localhost', port = DEFAULT_LOGGING_CONFIG_PORT, handler = None):
  330.             ThreadingTCPServer.__init__(self, (host, port), handler)
  331.             logging._acquireLock()
  332.             self.abort = 0
  333.             logging._releaseLock()
  334.             self.timeout = 1
  335.  
  336.         
  337.         def serve_until_stopped(self):
  338.             import select as select
  339.             abort = 0
  340.             while not abort:
  341.                 (rd, wr, ex) = select.select([
  342.                     self.socket.fileno()], [], [], self.timeout)
  343.                 if rd:
  344.                     self.handle_request()
  345.                 
  346.                 logging._acquireLock()
  347.                 abort = self.abort
  348.                 logging._releaseLock()
  349.  
  350.  
  351.     
  352.     def serve(rcvr, hdlr, port):
  353.         global _listener
  354.         server = rcvr(port = port, handler = hdlr)
  355.         logging._acquireLock()
  356.         _listener = server
  357.         logging._releaseLock()
  358.         server.serve_until_stopped()
  359.  
  360.     return threading.Thread(target = serve, args = (ConfigSocketReceiver, ConfigStreamHandler, port))
  361.  
  362.  
  363. def stopListening():
  364.     '''
  365.     Stop the listening server which was created with a call to listen().
  366.     '''
  367.     global _listener
  368.     if _listener:
  369.         logging._acquireLock()
  370.         _listener.abort = 1
  371.         _listener = None
  372.         logging._releaseLock()
  373.     
  374.  
  375.